package cm.hyb.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cm.hyb.Controller.model.Book;

@Controller   //相似于@Compenent
@RequestMapping("/Books")  //request的使用

@SessionAttributes(names= {"books"})  //session的使用
public class Books {
	
	
	private Logger logger = LoggerFactory.getLogger(Books.class);  //用来写日志
	private static List<Book> books = new ArrayList<>();
	{
		books.add(new Book("神雕侠侣",89.7,"渣渣"));
		books.add(new Book("绝代双娇",109.5,"古龙"));
		books.add(new Book("隋唐英雄传",129.3,"黄易"));
	}
	
	//查询所有
	@GetMapping("all")  //访问路径localhost:8080/Books/all
	public String findAll(Map<String, Object> map) {   //进入了request作用域
//		debug
//		info
//		warning
//		error
		logger.error("这就是我写出的日志！");
		map.put("books", books);
		return "bs/books";   //在配置文件里对bs/books进行处理，URL的尾部：spring.mvc.view.suffix=.jsp ，URL的头部：spring.mvc.view.prefix=/WEB-INF/jsp/
	}
	
	//删除
	@GetMapping("del")  //访问路径：localhost:8080/Books/del?name=神雕侠侣
	public String del(@RequestParam("name") String name) {
		books.remove(new Book(name,0.0,null));
		return "redirect:all";  //使用重定向 redirect:
		
	}
	
	//添加
	@GetMapping("adds")  
	public String add(@RequestParam("name") String name,double price,String auth ) {
		books.add(new Book(name,price,auth));
		return "redirect:all";
	}
	//从books.jsp跳转至addBooks.jsp的方法
	@GetMapping("add")
	public String add() {
		return "bs/addBooks";   
	}
	
	//修改
	@GetMapping("up")  //从books.jsp跳转至uoBooks的方法
	public String up() {
		return "bs/upBooks";
	}
		
	//获取jsp传输过来的name、price和auth，并将books集合进行遍历。
	@GetMapping("ups")
	public String up(@RequestParam("name") String name,double price,String auth) {
		for (Book book : books) {
			if((book.getName()).equals(name)) {
				book.setPrice(price);
				return "redirect:all";
			}
		}
		return "redirect:all";   //方法执行完毕后，重定向至：all方法
	}
	
	
}
